<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">企业名称：</span>
      <el-input v-model="dataParams.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" class="search-btn" @click="serchList">查询</el-button>
    </div>

    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button v-auth="'park:enterprise:add_edit'" type="primary" @click="$router.push('/addEnterprise')">添加企业</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <!-- @expand-change="expandChange"折叠事件 -->
      <el-table style="width: 100%" :data="tableData" @expand-change="expandChange">
        <el-table-column type="expand">
          <!-- 渲染数据 -->
          <template #default="props">
            <el-table :data="props.row.rentData">
              <el-table-column label="租赁楼宇" width="300" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" type="success" prop="status">
                <template #default="prop">
                  <el-tag :type="formatInfoType(prop.row.status)">
                    {{ formatStatus(prop.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{row}">
                  <el-button size="mini" type="text" :disabled="row.status === 3" @click="renewContract(row,props.row.id)">续租</el-button>
                  <!-- :disabled="row.status ===3"禁用按钮 -->
                  <el-button size="mini" type="text" :disabled="row.status === 3" @click="outRent(row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="row.status !== 3" @click="delRent(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{ row }">
            <el-button size="mini" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="LookRent(row.id)">查看</el-button>
            <el-button size="mini" type="text" @click="editEnterprice(row)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteEnterprise(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev,sizes, pager, next"
        :page-size="dataParams.pageSize"
        :total="total"
        :page-sizes="[2, 5,10,20]"
        @current-change="pageChage"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog
      :title="title"
      :visible="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单区域 -->
      <div class="form-container">
        <el-form ref="rentForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              style="width: 100%;"
              type="daterange"
              range-separator="至"
              :start-placeholder="title==='添加合同' ? '开始日期 ' : rentForm.rentTime[0]"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              action="#"
              :file-list="fileList"
              :http-request="uploadRequest"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBuildingRentAPI } from '@/api/building'
import { deleteEnterpriseAPI, getEnterpriseListAPI, uploadAPI, createRentAPI, getRentListAPI, outRentAPI, deleteRentAPI } from '@/api/Enterprise'
export default {
  data() {
    return {
      dataParams: {
        name: '',
        page: 1,
        pageSize: 5,
        contact: '',
        contactNumber: ''
      },
      tableData: [],
      total: 0,
      title: '',
      isEditing: false,
      // 控制弹层显示与隐藏
      rentDialogVisible: false,
      buildId: '',
      buildList: [],
      fileList: [],
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now()
        }
      }
    }
  },
  created() {
    this.getEnterpriseList()
    this.getRentBuildList()
  },
  methods: {
    // 企业列表
    async getEnterpriseList() {
      const { data } = await getEnterpriseListAPI({
        name: this.dataParams.name,
        page: this.dataParams.page,
        pageSize: this.dataParams.pageSize
      })
      console.log(data.rows)
      // 将折叠数据从新增变为修改
      const newData = data.rows.map(item => {
        return {
          ...item,
          rentData: []
        }
      })
      console.log(newData)
      this.tableData = newData
      this.total = data.total
    },
    // 分页器页码切换
    pageChage(val) {
      this.dataParams.page = val
      this.getEnterpriseList()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.dataParams.pageSize = val
      this.getEnterpriseList()
    },
    // 查询企业
    serchList() {
      this.dataParams.page = 1
      this.getEnterpriseList()
    },
    // 获取未租赁的楼宇列表
    async getRentBuildList() {
      const res = await getBuildingRentAPI()
      console.log(res)
      this.buildList = res.data
    },
    // 编辑企业
    editEnterprice(row) {
      console.log(row.id)
      this.$router.push({
        path: '/addEnterprise',
        query: {
          id: row.id
        }
      })
    },
    deleteEnterprise(row) {
      console.log(row)
      this.$confirm('确认删除嘛？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteEnterpriseAPI(row.id)
        if (res.code === 10000) {
          this.$message.success('删除成功' + res.msg)
          this.serchList()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 打开(添加合同)
    addRent(id) {
      console.log(id)
      // 清空表单
      this.rentForm = {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: id, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      }
      // 重置编辑状态
      this.isEditing = false

      this.rentDialogVisible = true
      this.title = '添加合同'
    },
    // 关闭弹层
    closeDialog() {
      this.rentDialogVisible = false
    },
    uploadRequest(data) {
      const formData = new FormData()
      console.log(data)

      formData.append('type', 'contract')
      formData.append('file', data.file)
      console.log(formData)

      uploadAPI(formData).then(res => {
        if (res.code === 10000) {
          this.rentForm.contractUrl = res.data.url // 绑定上传后的文件 URL
          this.rentForm.contractId = res.data.id // 如果有合同 ID
        } else {
          this.$message.error('文件上传失败：' + res.msg)
        }
      }).catch(() => {
        this.$message.error('网络请求失败，请稍后再试')
      })
    },
    // 上传前校验
    beforeUpload(file) {
      const allowedExtensions = ['doc', 'docx', 'pdf']
      const isValidExtension = allowedExtensions.includes(file.name.split('.').pop().toLowerCase())
      const isValidSize = file.size / 1024 / 1024 < 5 // 文件大小不超过 5MB

      if (!isValidExtension) {
        this.$message.error('仅支持 .doc, .docx, .pdf 格式的文件')
        return false
      }

      if (!isValidSize) {
        this.$message.error('文件大小不能超过 5MB')
        return false
      }

      return true
    },
    // 移除文件的方法
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 确认添加
    confirmAdd() {
      this.$refs.rentForm.validate(async valid => {
        if (valid) {
          if (this.title === '添加合同') {
            const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
            await createRentAPI({
              buildingId, contractId, contractUrl,
              enterpriseId: typeof enterpriseId === 'number' ? enterpriseId : parseInt(enterpriseId),
              type,
              startTime: this.rentForm.rentTime[0],
              endTime: this.rentForm.rentTime[1]
            }).then(res => {
              if (res.code === 10000) {
                this.$message.success('添加成功' + res.msg)
                this.rentDialogVisible = false
                this.resetForm()
                this.serchList()
              }
            })
          } else {
            await createRentAPI({
              buildingId: this.buildId,
              contractId: this.rentForm.contractId,
              contractUrl: this.rentForm.contractUrl,
              enterpriseId: this.rentForm.enterpriseId,
              type: this.rentForm.type,
              startTime: this.rentForm.rentTime[0],
              endTime: this.rentForm.rentTime[1]
            }).then(res => {
              if (res.code === 10000) {
                this.$message.success('修改成功')
                this.rentDialogVisible = false
                this.resetForm()
                this.serchList()
              }
            })
          }
        }
      })
    },
    // 获取合同列表
    async expandChange(row, rows) {
      // row代表当前行,rows代表展开所有行的数据
      console.log(row, rows)
      // 获取对应的合同列表
      const res = await getRentListAPI(row.id)
      console.log(res)
      // 将获取到的合同列表添加到这一行数据上
      // res.data就是展开table要渲染的数据
      // 不是新增一个rentData属性,而是直接修改原有的rantData属性
      // eslint-disable-next-line require-atomic-updates
      row.rentData = res.data
    },
    formatStatus(status) {
      // console.log('打印', row, column, cellValue, index)
      const statusMap = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return statusMap[status]
    },
    // 格式化tag类型
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      // return 格式化之后的中文显示
      return MAP[status]
    },
    // 修改退租状态
    outRent(id) {
      this.$confirm('确认退租嘛？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await outRentAPI(id)
        if (res.code === 10000) {
          this.$message.success('退租成功' + res.msg)
          // 刷新列表
          this.serchList()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    LookRent(id) {
      console.log(id)
      this.$router.push({
        path: '/lookEnterprise',
        query: {
          id
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.rentForm) {
        this.$refs.rentForm.resetFields() // 清空表单校验状态
      }
      // 手动重置 rentForm 的所有字段
      this.rentForm = {
        buildingId: null,
        contractId: null,
        contractUrl: '',
        enterpriseId: null,
        type: 0,
        rentTime: []
      }
    },
    // 续租回填数据
    renewContract(row, id) {
      this.rentDialogVisible = true
      this.isEditing = true
      this.title = '续租合同'
      // 设置表单数据
      console.log(id)
      this.rentForm.buildingId = row.buildingName
      this.rentForm.rentTime[0] = row.endTime
      this.rentForm.enterpriseId = parseInt(id)
      this.rentForm.type = 1
      this.buildId = row.buildingId
    },
    // 删除合同
    delRent(row) {
      this.$confirm('确认删除合同嘛？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteRentAPI(row.id)
        if (res.code === 10000) {
          this.$message.success('删除成功' + res.msg)
          // 刷新列表
          this.serchList()
        }
      }).catch(error => {
        console.log(error)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn{
    margin-left:20px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
